package action

import (
	"context"
	"time"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ActionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewActionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ActionListLogic {
	return &ActionListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ActionListLogic) ActionList(req *types.ActionListRo) (resp *types.ActionListRsp, err error) {
	sess := l.svcCtx.DB.WithContext(l.ctx).Model(&model.ActionConfig{})

	if req.ActionId != "" {
		sess = sess.Where("Id=?", req.ActionId)
	}
	if req.Name != "" {
		sess = sess.Where("Name=?", req.Name)
	}
	if req.Method != "" {
		sess = sess.Where("Method=?", req.Method)
	}
	if req.Path != "" {
		sess = sess.Where("Path=?", req.Path)
	}

	var total int64
	if err := sess.Count(&total).Error; err != nil {
		return nil, err
	}
	var beans []model.ActionConfig
	if err := sess.Order("ID DESC").Limit(req.Size).Offset((req.Page - 1) * req.Size).
		Find(&beans).Error; err != nil {
		return nil, err
	}

	resp = new(types.ActionListRsp)
	resp.Total = total
	for _, v := range beans {
		var ac = types.Action{
			ActionId:  v.ID,
			Name:      v.Name,
			Path:      v.Path,
			Method:    v.Method,
			Status:    int(v.Status),
			UpdatedAt: v.UpdatedAt.Format(time.RFC3339),
		}
		resp.Items = append(resp.Items, ac)
	}

	return
}
